<?php

namespace app\admin\controller;


use app\api\model\WeixinUser;
use app\common\lib\Show;
use app\common\lib\Status;
use app\common\model\MachineMachine;
use app\common\model\MallOrder;
use app\common\model\SystemAdmin;
use app\common\model\SystemQuick;
use app\common\controller\AdminController;
use Htlove\Time;
use think\App;
use think\facade\Cache;
use think\facade\Env;

class Index extends AdminController
{

    /**
     * 后台主页
     * @return string
     * @throws \Exception
     */
    public function index()
    {
        return $this->fetch('', [
            'admin' => session('admin'),
        ]);
    }

    /**
     * 后台欢迎页
     * @return string
     * @throws \Exception
     */
    public function welcome()
    {
        // 获取小程序新增
        $today = Time::getInstance()->today();
        $yesterday = Time::getInstance()->yesterday();
        $week = Time::getInstance()->week();
        $month = Time::getInstance()->month();


        $today_count = (new WeixinUser())->getBaseByListFind(array_merge([[
            ["create_time", 'between', $today]
        ]]), "count(id) as count");
        $yesterday_count = (new WeixinUser())->getBaseByListFind(array_merge([[
            ["create_time", 'between', $yesterday]
        ]]), "count(id) as count");
        $week_count = (new WeixinUser())->getBaseByListFind(array_merge([[
            ["create_time", 'between', $week]
        ]]), "count(id) as count");
        $month_count = (new WeixinUser())->getBaseByListFind(array_merge([[
            ["create_time", 'between', $month]
        ]]), "count(id) as count");

        $row = [
            "today" => $today_count['count'] ?? [],
            "yesterday" => $yesterday_count['count'] ?? [],
            "week" => $week_count['count'] ?? [],
            "month" => $month_count['count'] ?? [],
        ];
        $cate_machine = 1;
        if (!empty($this->request->cate_machine)) {
            $cate_machine = 2;
        }
        $this->assign('cate_machine',$cate_machine);
        return $this->fetch('', [
            "row" => $row
        ]);
    }

    /**
     * 修改管理员信息
     * @return string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function editAdmin()
    {
        $id = session('admin.id');
        $row = (new SystemAdmin())
            ->withoutField('password')
            ->find($id);
        empty($row) && $this->error('用户信息不存在');
        if ($this->request->isPost()) {
            $post = $this->request->post();
            $this->isDemo && $this->error('演示环境下不允许修改');
            $rule = [];
            $this->validate($post, $rule);
            try {
                $save = $row
                    ->allowField(['head_img', 'phone', 'remark', 'update_time'])
                    ->save($post);
            } catch (\Exception $e) {
                $this->error('保存失败');
            }
            $save ? $this->success('保存成功') : $this->error('保存失败');
        }
        $this->assign('row', $row);
        return $this->fetch();
    }

    /**
     * 修改密码
     * @return string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function editPassword()
    {
        $id = session('admin.id');
        $row = (new SystemAdmin())
            ->withoutField('password')
            ->find($id);
        if (!$row) {
            $this->error('用户信息不存在');
        }
        if ($this->request->isPost()) {
            $post = $this->request->post();
            $this->isDemo && $this->error('演示环境下不允许修改');
            $rule = [
                'password|登录密码' => 'require',
                'password_again|确认密码' => 'require',
            ];
            $this->validate($post, $rule);
            if ($post['password'] != $post['password_again']) {
                $this->error('两次密码输入不一致');
            }

            try {
                $save = $row->save([
                    'password' => password($post['password']),
                ]);
            } catch (\Exception $e) {
                $this->error('保存失败');
            }
            if ($save) {
                $this->success('保存成功');
            } else {
                $this->error('保存失败');
            }
        }
        $this->assign('row', $row);
        return $this->fetch();
    }
    /**
     * @return array|\think\response\Json
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getOrderByCount()
    {
        //查询本月天数
        $day_time = (int)date('t');  //本月总共多少天
        $today_time = (int)date('d'); //今日是第几天
        $key = "get_order_chunmai_" . date('Ym').$this->request->cate_machine;

        $obj = new MallOrder();
        $where = [];
        if(!empty($this->request->cate_machine)){
            //查询机器分类
            $machine = (new MachineMachine())->where('machine_cate',$this->request->cate_machine)
                ->select()->toArray();
            $where[] = [
                ['machine_id','in',array_column($machine,'machine_id')]
            ];
        }
        if ($today_time == 1) { //这是一个月的第一天
            //查询今日销售
            $today = $obj->getBaseByNormalListFind(array_merge([[
                ["create_time", "between", Time::getInstance()->today()],
                ["order_status",'<>',0]
            ]],$where), "sum(pay_price) as money,count(*) as count");
            $result = [
                "day" => [1],
                "money" => $this->getTodayNumber($today)
            ];
            return Show::json_show(Status::status_normal, "ok", $result);
        } else {  //不是一个月的第一天
            //查询所有
            $getCache = Cache::get($key);
            $list_data = [];
            $day = [];
            for ($i = 1; $i < $today_time; $i++) {
                $day[] = $i;
                //查询是否有缓存
                if ($getCache) {//存在缓存
                    //存在的缓存
                    if (empty($getCache[$i])) {
                        $ret = $obj->getOrderByOrderFind(array_merge([
                            ["create_time", "between", [
                                strtotime(date('Y-m-' . $i)), strtotime(date('Y-m-' . $i . " 23:59:59"))
                            ]],
                            ["order_status",'<>',0]
                        ],$where), "sum(pay_price) as money,count(*) as count");
                        $list_data[$i] = $this->getTodayNumber($ret);
                    }else{
                        $list_data[$i] = $getCache[$i];
                    }
                } else { //不存在缓存
                    $ret = $obj->getOrderByOrderFind(array_merge([[
                        ["create_time", "between", [
                            strtotime(date('Y-m-' . $i)), strtotime(date('Y-m-' . $i . " 23:59:59"))
                        ]],
                        ["order_status",'<>',0]
                    ]],$where), "sum(pay_price) as money,count(*) as count");
                    $list_data[$i] = $this->getTodayNumber($ret);
                }
            }
            if (!empty($list_data)) {
                Cache::set($key, $list_data);
            }
            $res = Cache::get($key);

//            "money"=>[
//                "name" => '销售金额',
//                "type" => 'bar',
//                "data" => [
//                    $today['money'] ?? 0
//                ],
//                "markPoint" => [
//                    "data" => [
//                        [
//                            "type" => 'max', "name" => 'Max'
//                        ],
//                        [
//                            "type" => 'min', "name" => 'Min'
//                        ],
//                    ]
//                ],
//                "markLine" => [
//                    "data" => [
//                        [
//                            "type" => 'average',
//                            "name" => 'Avg'
//                        ]
//                    ]
//                ]
//            ],
//            "number"=>[
//                "name" => '销售数量',
//                "type" => 'bar',
//                "data" => [
//                    $today['count'] ?? 0
//                ],
//                "markPoint" => [
//                    "data" => [
//                        [
//                            "type" => 'max', "name" => 'Max'
//                        ],
//                        [
//                            "type" => 'min', "name" => 'Min'
//                        ],
//                    ]
//                ],
//                "markLine" => [
//                    "data" => [
//                        [
//                            "type" => 'average',
//                            "name" => 'Avg'
//                        ]
//                    ]
//                ]
//            ]

            $day[] = (int)date('d');
            $today = $obj->getBaseByNormalListFind(array_merge([[
                ["create_time", "between", Time::getInstance()->today()]
            ]],$where), "sum(pay_price) as money,count(*) as count");
            $res[(int)date('d')]['number'] = $today['count'] ?? 0;
            $res[(int)date('d')]['money'] = $today['money'] ?? 0;
            $data = [
                [
                    "name" => '销售数量',
                    "type" => 'bar',
                    "data" => array_column($res, 'number'),
                    "markPoint" => [
                        "data" => [
                            [
                                "type" => 'max', "name" => 'Max'
                            ],
                            [
                                "type" => 'min', "name" => 'Min'
                            ],
                        ]
                    ],
                    "markLine" => [
                        "data" => [
                            [
                                "type" => 'average',
                                "name" => 'Avg'
                            ]
                        ]
                    ]
                ],
                [
                    "name" => '销售金额',
                    "type" => 'bar',
                    "data" => array_column($res, 'money'),
                    "markPoint" => [
                        "data" => [
                            [
                                "type" => 'max', "name" => 'Max'
                            ],
                            [
                                "type" => 'min', "name" => 'Min'
                            ],
                        ]
                    ],
                    "markLine" => [
                        "data" => [
                            [
                                "type" => 'average',
                                "name" => 'Avg'
                            ]
                        ]
                    ]
                ],
            ];
            $res_data = [
                "day" => $day ?? [],
                "data" => $data ?? []
            ];
            return Show::json_show(Status::status_normal, "ok", $res_data);

        }
    }
    /**
     * @param $today
     * @return array
     */
    protected function getTodayNumber($today)
    {
        return [
            "money" => $today['money'] ?? 0,
            "number" => $today['count'] ?? 0

        ];
    }

}
